let db = require('../db/dbmanager');
const log4js = require('../utils/logUtils');
const logger = log4js.getLogger('model');

/**
 * 服务器信息
 */
const TAG = "[Media Server Model]";
let MediaServer={
    cache:null,
    /**
     * 插入媒体服务器
     */
    insert: function(data){
        return new Promise(function (resolve) {
            let param = {
                $server_id_zlk: data.server_id_zlk,
                $intranet: data.intranet,
                $media_ip: data.media_ip,
                $http_port: data.http_port,
                $https_port: data.https_port,
                $rtmp_port: data.rtmp_port,
                $rtp_min_port: data.rtp_min_port,
                $rtp_max_port: data.rtp_max_port,
                $secret: data.zl_secret
            };
            const sql = "INSERT INTO MEDIASERVER(server_id_zlk,media_ip,intranet,http_port,https_port,rtmp_port,rtp_min_port,rtp_max_port,secret)VALUES($server_id_zlk,$media_ip,$intranet,$http_port,$https_port,$rtmp_port,$rtp_min_port,$rtp_max_port,$secret)";

            db.sqliteDB.run(sql, param);
            MediaServer.cache = null;
            db.sqliteDB.lastRow("DEVICE", (d) => {
                resolve(d);
            });
        });
    },
    /**
     * 更新媒体服务器信息
     */
    update: function(newdata, callback){
        let sqldata = {$server_id_zlk: newdata.server_id_zlk, $id: newdata.id};
        let newsql = '';
        if(newdata.server_id_zlk){
            sqldata.$server_id_zlk = newdata.server_id_zlk;
            if(newsql) newsql+=',';
            newsql += "server_id_zlk=$server_id_zlk";
        }
        if(newdata.media_ip){
            sqldata.$media_ip = newdata.media_ip;
            if(newsql) newsql+=',';
            newsql += "media_ip=$media_ip";
        }
        if(newdata.intranet){
            sqldata.$intranet = newdata.intranet;
            if(newsql) newsql+=',';
            newsql += "intranet=$intranet";
        }
        if(newdata.http_port){
            sqldata.$http_port = newdata.http_port;
            if(newsql) newsql+=',';
            newsql += "http_port=$http_port";
        }
        if(newdata.https_port){
            sqldata.$https_port = newdata.https_port;
            if(newsql) newsql+=',';
            newsql += "https_port=$https_port";
        }
        if(newdata.rtmp_port){
            sqldata.$rtmp_port = newdata.rtmp_port;
            if(newsql) newsql+=',';
            newsql += "rtmp_port=$rtmp_port";
        }
        if(newdata.rtp_min_port){
            sqldata.$rtp_min_port = newdata.rtp_min_port;
            if(newsql) newsql+=',';
            newsql += "rtp_min_port=$rtp_min_port";
        }
        if(newdata.rtp_max_port){
            sqldata.$rtp_max_port = newdata.rtp_max_port;
            if(newsql) newsql+=',';
            newsql += "rtp_max_port=$rtp_max_port";
        }
        if(newdata.zl_secret){
            sqldata.$secret = newdata.zl_secret;
            if(newsql) newsql+=',';
            newsql += "secret=$secret";
        }
        const sql = "update MEDIASERVER set " + newsql + " where id=$id";
        logger.info(sql, sqldata);
        db.sqliteDB.run(sql,sqldata);
        MediaServer.cache=null;
        if(callback){
            callback(newdata);
        }
    },
    del:function(id){
        let param={
            $id: id
        };
        const sql = "DELETE FROM MEDIASERVER WHERE id=$id";
        db.sqliteDB.run(sql,param);
        MediaServer.cache = null;
    },
    getDefault:async function(){
        if(!MediaServer.cache){
            await MediaServer.reloadCache();
        }
        const server = MediaServer.cache[0];
        return this.getInfoById(server.id);
    },
    getById:async function(id){
        if(!MediaServer.cache){
            await MediaServer.reloadCache();
        }
        return new Promise(function (resolve) {
            let item = MediaServer.cache.find((value) => {
                return value.id === parseInt(id)
            });
            resolve(item)
        });
    },
    getByServerId: function(server_id_zlk){
        return new Promise(async function(resolve){
            if(!MediaServer.cache || !MediaServer.cache.secret){
                await MediaServer.reloadCache();
            }
            let item = MediaServer.cache.find((value)=>{
                return value.server_id_zlk === server_id_zlk
            });
            if(!item){
                await MediaServer.reloadCache();
                item = MediaServer.cache.find((value)=>{
                    return value.server_id_zlk === server_id_zlk
                });
            }
            resolve(item);
        });
    },
    reloadCache: function(){
        return new Promise(function (resolve) {
            if (!MediaServer.cache|| !MediaServer.cache.secret) {
                const sql = "SELECT * from MEDIASERVER order by id DESC";
                db.sqliteDB.queryData(sql, function (rows) {
                    MediaServer.cache = Object.assign(rows);
                    resolve(MediaServer.cache);
                });
            } else {
                resolve(MediaServer.cache);
            }
        });
    },
    /**
     * 查询列表
     * @param {*} page 第几页
     * @param {*} size 每页大小
     */
    list:function(page,size){
        return new Promise(function (resolve) {
            if (MediaServer.cache) {
                resolve(MediaServer.cache);
            } else {
                const sql = `SELECT * from MEDIASERVER order by id DESC limit ${size} offset ${size}*${page-1}`;
                db.sqliteDB.queryData(sql, function (rows) {
                    MediaServer.cache = Object.assign(rows);
                    resolve(MediaServer.cache);
                });
            }
        });
    },
    count:function(){
        return new Promise(function (resolve) {
            let sql = "SELECT COUNT(*) as c FROM MEDIASERVER";
            db.sqliteDB.oneData(sql, (ret) => {
                resolve(ret.c);
            });
        });
    },
    getInfoById: async function(id){
        return new Promise(async function (resolve, reject) {
            let item = await MediaServer.getById(id);
            if (item) {
                resolve(Object.assign({
                    // 这个地址用来请求ZLMediaKit的API使用
                    zlk_api_host: `http://${item.intranet}:${item.http_port}/`,
                    url: `http://${item.media_ip}:${item.http_port}/`,
                    urlTls: `https://${item.media_ip}:${item.https_port}/`,
                    rtmp: `rtmp://${item.media_ip}:${item.rtmp_port}/`,
                    rtmp_snap: `rtmp://${item.media_ip}:${item.rtmp_port}/`
                },item));
            } else {
                reject();
            }
        });
    },
    getInfoByServerId :async function(serverId){
        const item = await MediaServer.getByServerId(serverId);
        if (item) {
            return (Object.assign({
                // 这个地址用来请求ZLMediaKit的API使用
                zlk_api_host: `http://${item.intranet}:${item.http_port}/`,
                url: `http://${item.media_ip}:${item.http_port}/`,
                urlTls: `https://${item.media_ip}:${item.https_port}/`,
                rtmp: `rtmp://${item.media_ip}:${item.rtmp_port}/`,
                rtmp_snap: `rtmp://${item.media_ip}:${item.rtmp_port}/`
            },item));
        }
    }
};

module.exports=MediaServer;
